
type RequestMethod = 'GET' | 'POST' | 'OPTIONS' | 'HEAD' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT' | undefined

export function baseRequest<T = any>(apiCode : string, data : any, method : RequestMethod = 'GET') : Promise<T> {
	return new Promise((resolve, reject) => {
		// 获取 token
		const token = uni.getStorageSync('token')
		const header: any = {
			'X-Host': apiCode,
		}
		// 将 token 写入请求头
		if (token) {
			header['Authorization'] = token
		}
		uni.request({
			url: 'https://m.maizuo.com/gateway/?apiCode=' + apiCode,
			data,
			method,
			header,
			success: (res) => {
				// 获取接口返回值
				const { status, msg, data } = res.data as any
				// 判断业务状态码
				switch (status) {
					case 0:
						// 成功
						// 		1. 直接返回的数据为 接口的 data
						resolve(data)
						break;
					default:
						// 失败
						// 		1. Toast 提示
						uni.showToast({
							icon: 'none',
							title: msg
						})
						// 		2. reject
						reject(res.data)
						break;
				}
			},
			fail: (error) => {
				// 可以判断http状态码
				console.log('fail', error)

				reject(error)
			}
		})
	})
}

const request = {
	get: <T = any>(apiCode : string, data : any) => baseRequest<T>(apiCode, data, 'GET'),
	post: <T = any>(apiCode : string, data : any) => baseRequest<T>(apiCode, data, 'POST')
}

export default request